/*
 * 367dns JavaScript Library
 * Copyright (c) 2014 367dns.com
 */
//var server = "http://192.168.1.104/my/";
//var socket_url = "http://192.168.1.104:2120";
var APP_POST = 'uys62gkqVtYaQAO0';
var APP_GET = 'lEWDllVsvWK8seMf';
//var server = "http://192.168.0.105:8003/paopao/";
//var server = "https://47.107.77.215/AlanMB_10.2.700/api/v1/";
//var server = "https://42.200.200.226/UAT_102700/api/v1/";
var server = " https://47.107.77.215/DemoWMS/api/v1/";
var apiserver = "https://47.107.77.215/DemoWMS/api/v1/";
// 科迪华
// var server = "https://192.168.10.100/CRP01/api/v1/";
// var apiserver = "http://192.168.10.100:8080/CRP01/";
var wmsserver = "https://47.107.77.215:8080/DemoWMS/";
var wmstoken = "HBpYjM1QzNzg3m-ZIcN1c3Qtc2VuLWG2tcHZjIZjE0MWQxMOWQwYQ2186MDF5QYjA5mUxj0YAuaWamVi";

var searchnewsurl = server+'appsearchnews';
var searchfaqurl = server+'appsearchfaq';
var appversion = "";
var SiteName = "";
var CompanyName = ""
var userinfo
var andappversion = '102';
var debug = 1;
var ajaxing = 0;
var is_scan = 0;
var apppackage = "com.zhihu.juxindai";
var isaes = '0';
var lkey = localStorage.getItem('lkey')?localStorage.getItem('lkey'):'en-hk'
var lan = lang[lkey];
server =localStorage.getItem('customapi')?localStorage.getItem('customapi'):"https://47.107.77.215/DemoWMS/api/v1/";
apiserver=localStorage.getItem('customapi')?localStorage.getItem('customapi'):"https://47.107.77.215/DemoWMS/api/v1/";
wmsserver = localStorage.getItem('wmsapi')?localStorage.getItem('wmsapi'):"http://47.107.77.215:8080/DemoWMS/";
var modelpda = localStorage.getItem('pda')?localStorage.getItem('pda'):'tsc'
var modeldayin = localStorage.getItem('dayin')?localStorage.getItem('dayin'):'tsc'


function getlan(){
  var customkey = api.getPrefs({sync:true,key:'lkey'});
  alert(customkey);
  if(customkey){
    lan = lang[customkey];
  }else{
    lan = lang[lkey];
  }
}

function getapi(){
  var customapi = api.getPrefs({sync:true,key:'api'});
  if(customapi){
     return customapi;
  }else{
     return apiserver;
  }
}

function toLogin(){
    //opencomWin ('login',{bounces:0,frame:'login1',title:'登录'})

    var data = {};
    data.title =  '';
    data.frame = 'login';
    data.hideBackButton=true;
    data.hideNavigationBar=true;
    data.right = [{
      text: lan['Setting'],//（可选项）按钮标题文字，可以和icon同时存在，字符串类型
      color: '#fff',//（可选项）按钮标题文字颜色，默认值#000，字符串类型
      //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
      //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
      //iconPath: //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
   }];
   

    openNavWin2(data.frame,data);
}






function toNavWin(ob){
  var data = {};
  var login = parseInt($(ob).data("login"))
  if(login){
    userinfo = get_user_info();
    if(!userinfo.Token){
      toLogin();
      return;
    }

  }
  if($(ob).data("id")){
   data.id =  $(ob).data("id");
  }
  data.title =  $(ob).data("title");
  data.frame = $(ob).data("frame");
  var right = $(ob).data("right");
  if(right){
  data.right = [{
      text: right,//（可选项）按钮标题文字，可以和icon同时存在，字符串类型
      color: '#000',//（可选项）按钮标题文字颜色，默认值#000，字符串类型
      //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
      //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
      //iconPath: //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
   }];
   }
  openNavWin(data.frame,data);
}

function toNavWin2(ob){
  var login = parseInt($(ob).data("login"))
  if(login){
    userinfo = get_user_info();
    if(!userinfo.Token){
      toLogin();
      return;
    }
  }
  let datas = {
      DeviceID: api.deviceId,
      LicQty: app.LicQty,
  }
  Loginout_Userchklic(datas,function(ret){
    console.log(JSON.stringify(ret), 111111)
    if(ret == 200){

      var data = {};
      data.title =  $(ob).data("title");
      data.frame = $(ob).data("frame");
      var right = $(ob).data("right");

      if(right){
      data.right = [{
          text: right,//（可选项）按钮标题文字，可以和icon同时存在，字符串类型
          color: '#fff',//（可选项）按钮标题文字颜色，默认值#000，字符串类型
          //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
          //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
          //iconPath: //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
      }];
      } 
        if(data.frame == "buy_detial" || data.frame == "order_material" || data.frame == "deliver_products" || data.frame == "deliver_products_new"){
        user_Permissions(data).then(function(result) {
          // 权限判断通过，进行页面跳转
          openNavWin2(data.frame, data);
        }).catch(function(error) {
          // 权限判断未通过，处理相关逻辑
          console.log(error);
        });
      } else {
        openNavWin2(data.frame, data);
      }


    }else{
      api.confirm({
        title:lan['Tips'],
        msg: lan['Login_Timed'],
        buttons: [lan['Cancel'],lan['OK']]
       }, function(ret, err) {
         var index = ret.buttonIndex;
         if(index == 2){
             toLogin();
         }
       });
    }
    
  })
  
}

function openNavWin(winname,data){
    var param = {
      name: winname,
      url: api.wgtRootDir + '/html/' + data.frame + '.html',
      title: data.title,
      bounces: false,
      bgColor:'#e4e4e4',
      pageParam: data,
      navigationBar: {
          background: '#00b3f6',
          color: '#fff',
          shadow: '#fff',
          fontSize:18,                 //（可选项）导航栏标题字体大小。默认值17，数字类型
          fontWeight: 'bold',              //（可选项）导航栏标题字体粗细。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
          //hideBackButton:           //（可选项）是否隐藏默认返回按钮。如果传了leftButtons，hideBackButton参数失效。返回按钮由箭头图标和前一个页面的标题组成，若前一个页面未设置标题，则按钮文字为“返回”。可以通过监听navbackbtn或keyback事件来处理返回按钮的点击事件。布尔类型

          leftButtons: //（可选项）导航栏左边按钮组。左边按钮会替换掉默认的返回按钮，按钮按照数组顺序从左至右显示，按钮建议最多2个，可以通过监听navitembtn事件来处理按钮点击事件，JSON对象数组类型
              [{
                  text: '   ', //（可选项）按钮标题文字，可以和icon同时存在，字符串类型
                  //color:'#fff', //（可选项）按钮标题文字颜色，默认值#000，字符串类型
                  //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
                  //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
                  iconPath:"widget://images/back.png", //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
          }],
          /*
          rightButtons: //（可选项）导航栏右边按钮组。按钮按照数组顺序从右至左显示，按钮建议最多2个，可以通过监听navitembtn事件来处理按钮点击事件，JSON对象数组类型
              [{
                  text: '兑换中心',//（可选项）按钮标题文字，可以和icon同时存在，字符串类型
                  color: '#fff',//（可选项）按钮标题文字颜色，默认值#000，字符串类型
                  //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
                  //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
                  //iconPath: //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
          }]
          */
      }

  }
  if(data.right){
    param.navigationBar.rightButtons = data.right;
  }
  api.openTabLayout(param);
}

function openNavWin2(winname,data){
    var param = {
      name: winname,
      url: api.wgtRootDir + '/html/' + data.frame + '.html',
      title: data.title,
      hideNavigationBar:data.hideNavigationBar,
      hideBackButton:data.hideBackButton,
      bounces: false,
      useWKWebView: true,
      bgColor:'#e4e4e4',
      pageParam: data,
      navigationBar: {
          background: '#00b3f6',
          color: '#fff',
          shadow: '#ddd',
          fontSize:18,                 //（可选项）导航栏标题字体大小。默认值17，数字类型
          fontWeight: 'bold',              //（可选项）导航栏标题字体粗细。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
          //hideBackButton:           //（可选项）是否隐藏默认返回按钮。如果传了leftButtons，hideBackButton参数失效。返回按钮由箭头图标和前一个页面的标题组成，若前一个页面未设置标题，则按钮文字为“返回”。可以通过监听navbackbtn或keyback事件来处理返回按钮的点击事件。布尔类型

          leftButtons: //（可选项）导航栏左边按钮组。左边按钮会替换掉默认的返回按钮，按钮按照数组顺序从左至右显示，按钮建议最多2个，可以通过监听navitembtn事件来处理按钮点击事件，JSON对象数组类型
              [{
                  text: '   ', //（可选项）按钮标题文字，可以和icon同时存在，字符串类型
                  color:'#fff', //（可选项）按钮标题文字颜色，默认值#000，字符串类型
                  //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
                  //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
                  iconPath:"widget://image/drawable007c.png", //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
          }],
          /*
          rightButtons: //（可选项）导航栏右边按钮组。按钮按照数组顺序从右至左显示，按钮建议最多2个，可以通过监听navitembtn事件来处理按钮点击事件，JSON对象数组类型
              [{
                  text: '兑换中心',//（可选项）按钮标题文字，可以和icon同时存在，字符串类型
                  color: '#fff',//（可选项）按钮标题文字颜色，默认值#000，字符串类型
                  //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
                  //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
                  //iconPath: //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
          }]
          */
      }

  }
  if(data.right){
    param.navigationBar.rightButtons = data.right;
  }
  api.openTabLayout(param);
}


function back_listen(){
   api.addEventListener({ name:'navitembtn' },function(ret, err){ api.closeWin({}); });
}
function close_win(){
  api.closeWin({});
}
function opencomWin (winname,Param) {

    var delay = 0;
     if(api.systemType != 'ios'){
            delay = 300;
    }

	api.openWin({
		name:winname,
		url: './common_header.html',
		vScrollBarEnabled:false,
		delay:delay,
		allowEdit:true,
    softInputMode:'auto',
		pageParam:Param
	});
}

function openWin (winname,path,Param) {

    var delay = 0;
     if(api.systemType != 'ios'){
            delay = 300;
    }

	api.openWin({
		name:winname,
		url: path,
		vScrollBarEnabled:false,
		delay:delay,
		pageParam:Param
	});
}

function toUrl(ob){
  var url = $(ob).attr("data-url");
  var title = $(ob).attr("data-title");
  if(!url){return;}


  var param = {
    name: 'url',
    url: url,
    title: title,
    bounces: true,
    useWKWebView: true,
    bgColor:'#e4e4e4',
    pageParam: {},
    navigationBar: {
        background: '#e65603',
        color: '#fff',
        shadow: '#ddd',
        fontSize:18,                 //（可选项）导航栏标题字体大小。默认值17，数字类型
        fontWeight: 'bold',              //（可选项）导航栏标题字体粗细。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
        //hideBackButton:           //（可选项）是否隐藏默认返回按钮。如果传了leftButtons，hideBackButton参数失效。返回按钮由箭头图标和前一个页面的标题组成，若前一个页面未设置标题，则按钮文字为“返回”。可以通过监听navbackbtn或keyback事件来处理返回按钮的点击事件。布尔类型
        /*
        leftButtons: //（可选项）导航栏左边按钮组。左边按钮会替换掉默认的返回按钮，按钮按照数组顺序从左至右显示，按钮建议最多2个，可以通过监听navitembtn事件来处理按钮点击事件，JSON对象数组类型
            [{
                text: '   ', //（可选项）按钮标题文字，可以和icon同时存在，字符串类型
                color:'#fff', //（可选项）按钮标题文字颜色，默认值#000，字符串类型
                //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
                //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
                iconPath:"widget://image/drawable007c.png", //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
        }],
        */
        /*
        rightButtons: //（可选项）导航栏右边按钮组。按钮按照数组顺序从右至左显示，按钮建议最多2个，可以通过监听navitembtn事件来处理按钮点击事件，JSON对象数组类型
            [{
                text: '兑换中心',//（可选项）按钮标题文字，可以和icon同时存在，字符串类型
                color: '#fff',//（可选项）按钮标题文字颜色，默认值#000，字符串类型
                //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
                //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
                //iconPath: //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
        }]
        */
    }

}

api.openTabLayout(param);
  //alert(title);
  //openWin('ad',api.wgtRootDir+'/html/common_header_link.html',{bounces:1,url:url,title:title});
}



function topageUrl(data){
  var url = data.url;
  var title = data.title;
  if(!url){return;}


  var param = {
    name: 'url',
    url: url,
    title: title,
    bounces: true,
    useWKWebView: true,
    bgColor:'#e4e4e4',
    pageParam: {},
    navigationBar: {
        background: '#e65603',
        color: '#fff',
        shadow: '#ddd',
        fontSize:18,                 //（可选项）导航栏标题字体大小。默认值17，数字类型
        fontWeight: 'bold',              //（可选项）导航栏标题字体粗细。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
        //hideBackButton:           //（可选项）是否隐藏默认返回按钮。如果传了leftButtons，hideBackButton参数失效。返回按钮由箭头图标和前一个页面的标题组成，若前一个页面未设置标题，则按钮文字为“返回”。可以通过监听navbackbtn或keyback事件来处理返回按钮的点击事件。布尔类型
        /*
        leftButtons: //（可选项）导航栏左边按钮组。左边按钮会替换掉默认的返回按钮，按钮按照数组顺序从左至右显示，按钮建议最多2个，可以通过监听navitembtn事件来处理按钮点击事件，JSON对象数组类型
            [{
                text: '   ', //（可选项）按钮标题文字，可以和icon同时存在，字符串类型
                color:'#fff', //（可选项）按钮标题文字颜色，默认值#000，字符串类型
                //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
                //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
                iconPath:"widget://image/drawable007c.png", //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
        }],
        */
        /*
        rightButtons: //（可选项）导航栏右边按钮组。按钮按照数组顺序从右至左显示，按钮建议最多2个，可以通过监听navitembtn事件来处理按钮点击事件，JSON对象数组类型
            [{
                text: '兑换中心',//（可选项）按钮标题文字，可以和icon同时存在，字符串类型
                color: '#fff',//（可选项）按钮标题文字颜色，默认值#000，字符串类型
                //fontSize: //（可选项）按钮标题字体大小。默认值17，数字类型
                //fontWeight: //（可选项）按钮标题字体粗细，默认值normal。字符串类型。Android及iOS8.2以下系统只支持normal、bold，iOS8.2及以上系统支持normal、bold、bolder、lighter、100~900。
                //iconPath: //（可选项）按钮icon图标路径，可以和text同时存在，图片尺寸需要为4倍图，例如设备上面期望显示的图标尺寸为25*25，则图片实际尺寸需要为100*100，字符串类型
        }]
        */
    }

}

api.openTabLayout(param);
  //alert(title);
  //openWin('ad',api.wgtRootDir+'/html/common_header_link.html',{bounces:1,url:url,title:title});
}

function toadUrl(ob){
  var url = $(ob).attr("data-url");
  var title = $(ob).attr("data-title");
  if(!url){return;}
   var systemType = api.systemType;
   if(systemType == "android"){
          open_url(url);
   }
   if(systemType == "ios"){
     api.openApp({
             iosUrl : url, //打开微信的，其中weixin为微信的URL Scheme
     });
   }
  //alert(title);
  //openWin('ad',api.wgtRootDir+'/html/common_header_link.html',{bounces:1,url:url,title:title});
}
function open_url(uri){
  api.openApp({
androidPkg: 'android.intent.action.VIEW',
mimeType: 'text/html',
uri: uri
}, function(ret, err) {
if (ret) {
    //alert(JSON.stringify(ret));
} else {
    //alert(JSON.stringify(err));
}
});
}

function showProgress(text){
  ajaxing = 1;
  api.showProgress({title: text,text:'',style: 'zoom'});
}
function hideProgress(){
  ajaxing = 0;
  api.hideProgress();
}

function closewin (winname) {
	api.closeWin({name:winname});
}

function openNewframe(frame,path, marginTop,height,isBounce,param) {
    api.openFrame({
        name: frame,
        url: path,
        rect: {
            x: 0,
            y: marginTop,
            w: 'auto',
            h: height
        },
        pageParam: param,
        bounces: isBounce,
        vScrollBarEnabled: false,
        hScrollBarEnabled: false,
        delay: 200
    });
}

function openShare (frame,path,param) {
	api.openFrame({
		name: frame,
		url: path,
		pageParam: param,
		bounces: false,
		opaque: false,
		delay:200,
		rect: {
			x: 0,
			y: 0,
			w: 'auto',
			h: 'auto'
		}

	});
}
function closeWin(){
  api.closeWin({});
}
function alert_err(err){
   api.alert({msg:err.msg});
}

function data_update(){
   apiready();
}

function closeTips(){

	$api.remove($api.byId("aui-tips"));
	api.sendEvent({
                    name : 'notify',
                    extra : {'action':'colse_notify','sms':1}
    });
}
function notify_msn(sms){
    $api.remove($api.byId("aui-tips"));
	var dom_body = $api.dom('body');
	$api.append(dom_body,sms);
}
function listen_notify(){


    api.addEventListener({
          name : 'notify'
    }, function(ret) {
        if (ret && ret.value) {
           var data = ret.value;
           //alert(JSON.stringify(data.action));
           if(data.action == "new_sms"){
              var output = data.sms;
              notify_msn(output);
              if(api.winName == 'root'){
                 var newsms_status = document.getElementById("newsms_status");
                 $api.html(newsms_status,'<span class="aui-dot"></span>');
              }
           }


           if(data.action == "colse_notify"){
              $api.remove($api.byId("aui-tips"));
           }

           if(data.action == "sms_status"){
              if(api.winName == 'root'){
                 var newsms_status = document.getElementById("newsms_status");
                 if(data.sms > 0){
                 $api.html(newsms_status,'<span class="aui-dot"></span>');
                 }else{
                 $api.html(newsms_status,'');
                 }

              }
           }

        }
   });

}
function ajaxstart (offset,refresh) {
  ajaxing = 1;
  if(offset == 0){if(refresh == 0){api.showProgress()};}else{ $("#more_loading").show(); }
}
function ajaxstop (offset,refresh) {
  ajaxing = 0;
  if(offset == 0){if(refresh == 0){api.hideProgress();}else{api.refreshHeaderLoadDone();}}else{  $("#more_loading").hide();}
}
function get_user_info(){
    var user_str = api.getPrefs({sync:true,key:'userinfo'});
    appversion = api.appVersion;
    var userinfo = {};
    userinfo.id = 0;
    userinfo.Token = 0;
    if(user_str){
       userinfo = $api.strToJson(user_str);
       userinfo.uid = userinfo.id;
       CompanyName = userinfo.CompanyName;
       SiteName = userinfo.SiteName;
    }
    return userinfo;
}


function html_faved(ob){
  var status = parseInt($(ob).attr("data-status"));
  var id = $(ob).attr("data-id");
  var type = $(ob).attr("data-type");
  var count = $(ob).attr("data-count");
  if(status == 0){
     $(ob).addClass("on");
     $(ob).addClass("zaned");
     $(ob).addClass("active");
     $(ob).attr("data-status",1);
     if(count != "undefined"){
     count++;
     $("#favedcount"+id).html(count);
     $(ob).attr("data-count",count);
     $("#favedcount"+id).addClass("animated");
      }
     //api.toast({msg :'已关注！',location: 'middle'});
  }else{

     $(ob).removeClass("on");
      $(ob).removeClass("zaned");
       $(ob).removeClass("active");
     $(ob).attr("data-status",0);
     if(count != "undefined"){
     count--;
     $(ob).attr("data-count",count);
     $("#favedcount"+id).html(count);
   }

     //api.toast({msg :'已取消！',location: 'middle'});
  }
}


function html_termfaved(ob){
  var status = parseInt($(ob).attr("data-status"));
  var id = $(ob).attr("data-id");
  var type = $(ob).attr("data-type");


  var count = parseInt($("#itemtag"+id).attr("data-follow"));

  if(status == 0){
     $(ob).addClass("active");
     $(ob).attr("data-status",1);
     $(ob).html("已关注");
     count++;
     $("#itemtag"+id).attr("data-follow",count);
     $("#itemtag"+id).attr("data-collection",1);
     $("#followcount"+id).html(count);
  }else{
     $(ob).removeClass("active");
     $(ob).attr("data-status",0);
     $(ob).html("+关注");
     count--;
     $("#itemtag"+id).attr("data-follow",count);
     $("#itemtag"+id).attr("data-collection",0);
     $("#followcount"+id).html(count);
   }

}

function faved_update(ret){
  var data = ret.value;
  var id = data.object_id;
  if(data.faved_status == 0){
     $("#faved"+id).addClass("active");
     $("#faved"+id).attr("data-status",1);
     $("#faved"+id).html("已关注");
     $("#itemtag"+id).attr("data-follow",data.count);
     $("#itemtag"+id).attr("data-collection",1);
  }else{
     $("#faved"+id).removeClass("active");
     $("#faved"+id).attr("data-status",0);
     $("#faved"+id).html("+关注");
     $("#itemtag"+id).attr("data-follow",data.count);
     $("#itemtag"+id).attr("data-collection",0);
   }
}

function checkPhone(phone) {
      var res = !!phone.match(/^[1][3,4,5,7,8][0-9]{9}$/);
      return res;
 }

function html_commetfaved(ob){
  var status = parseInt($(ob).attr("data-status"));
  var id = $(ob).attr("data-id");
  var type = $(ob).attr("data-type");
  var count = $(ob).attr("data-count");
  if(status == 0){
     $(ob).addClass("on");
      $(ob).addClass("active");
     $(ob).attr("data-status",1);
     count++;
     $("#voter_count"+id).html(count);
     $(ob).attr("data-count",count);
     $(ob).addClass("animated");
  }else{

     $(ob).removeClass("on");
      $(ob).removeClass("active");
     $(ob).attr("data-status",0);
     count--;
     $(ob).attr("data-count",count);
      $("#voter_count"+id).html(count);

     //api.toast({msg :'已取消！',location: 'middle'});
  }
}

function html_userfaved(ob){
  var status = parseInt($(ob).attr("data-status"));
  var id = $(ob).attr("data-id");
  var type = $(ob).attr("data-type");
  if(status == 0){
     $(ob).addClass("on");
     $(ob).attr("data-status",1);
     $("#usercount"+id).html('已关注');
  }else{

     $(ob).removeClass("on");
     $(ob).attr("data-status",0);
    $("#usercount"+id).html('+关注');

     //api.toast({msg :'已取消！',location: 'middle'});
  }
}

function imgOpen(id,index) {

      var imgs = [];
      var imgsob = $("#imgs"+id+" img");
      imgsob.each(function(){
        var full = $(this).attr("data-full");
        imgs.push(full);
      });

      api.openWin({
            name: 'photobrowser',
            url: './photobrowser.html',
            pageParam:{imgs:imgs,index:index},
            animation:{
                 type:"fade",                //动画类型（详见动画类型常量）
                 //subType:"from_bottom",       //动画子类型（详见动画子类型常量）
                 duration:300                //动画过渡时间，默认300毫秒
            }

     })

}

function dofaved(ob){
  var status = parseInt($(ob).attr("data-status"));
  var id = $(ob).attr("data-id");
  var type = $(ob).attr("data-type");
  var count = $(ob).attr("data-count");
  var callback = parseInt($(ob).attr("data-callback"));

  userinfo = get_user_info();
  if(!userinfo.Token){
    toLogin();
    return;
  }
  if(ajaxing){ return; }
  //if(status == '1'){ return; }
  if(type == 'user'){
     html_userfaved(ob);
  }else if(type == 'comment'){
     html_commetfaved(ob);
  }else if(type == 'term'){
     html_termfaved(ob);
  }else{
     html_faved(ob);
  }

  var data1 = {"token":userinfo.Token,"data":{"object_id":id,action:'add_faved',type:type,status:status}};
  ajaxing = 1;//防止重复提交
  api.ajax({
         url: server+'api/user.php',
         method : 'post',
         returnAll : false,
         data: {body: create_post_data(data1)}
    },function(ret, err){
       ajaxing = 0;
       console_debug(ret,err);
       if(ret){
        if (ret.status == 1) {
           //
           if(callback){
               faved_callback(ret);
           }
        }else{
             api.toast({ msg : ret.error,location: 'middle'});
        }

      }else{
        api.alert({msg:err.msg});
      }
    });
}


function  jubao(ob){



   var userid = $(ob).attr("data-userid");
   var jubao  = $(ob).attr("data-status");
   var id = $(ob).attr("data-id");
   var type = $(ob).attr("data-type");



   userinfo = get_user_info();
   if(!userinfo.Token){
     toLogin();
     return;
   }
   if(ajaxing){ return; }
   var data1 = {"token":userinfo.Token,"data":{"type":type,"userid":userid,"id":id,"status":jubao,"action":'jubao'}};
   ajaxing = 1;
   api.ajax({
         url: server+'/api/user.php',
         method : 'post',
         returnAll : false,
         data: {body: create_post_data(data1)}
    },function(ret, err){
       ajaxing = 0;
       console_debug(ret,err);
       if(ret){
        if (ret.status == 1) {
           if(jubao == 0){
              $(ob).attr("data-status",1);
              $(ob).html("已举报");
              api.toast({msg :ret.output,location: 'middle'});
           }else{
              $(ob).attr("data-status",0);
              $(ob).html("举报");
              api.toast({msg :'已取消举报!'});
           }

        }else{
           api.toast({ msg : ret.error,location: 'middle'});
        }
      }else{
        api.alert({msg:err.msg});
      }

    });





}


function get_member_info(){

   if(!api.connectionType){
       return false;
   }

   var userinfo = get_user_info();
   if(!userinfo.Token){
      return false;
   }
   var data1 = {"token":userinfo.Token,"data":{"userid":userinfo.id,"action":'refresh_user'}};
   console_debug(data1,data1);
   api.ajax({
         url: server+'/api/user.php',
         method : 'post',
         returnAll : false,
         data: {body: create_post_data(data1)}
    },function(ret, err){
        
       console_debug(ret,err);
       if(ret.status == 1){
           api.setPrefs({key:'userinfo',value : ret.data});
           userinfo = ret.data;
           api.sendEvent({name : 'userinfo_update',extra : 'update'});
       }else{
         clear_userinfo();
         api.sendEvent({name : 'userinfo_update',extra : 'update'});
         api.sendEvent({name : 'reg_login_successEvent',extra : 'update'});
         return;
         api.confirm({
           title: '提示',
           msg: '用户信息过期了，请重新登录？',
           buttons: ['确定', '取消']
          }, function(ret, err) {
            var index = ret.buttonIndex;
            if(index == 1){
                toLogin();
            }
          });
       }

    });

}
function clear_userinfo(){
  api.removePrefs({key: 'userinfo'});
  api.removePrefs({key: 'PartNumList'});
  localStorage.removeItem('PartNumList')
}
function get_prefs_data(key){
  var data_str = api.getPrefs({sync:true,key:key});
  var data;
  if(data_str){
     data = $api.strToJson(data_str);
  }
  return data;
}
function console_debug(ret,err){
   if(debug == 1){
      console.log('success:'+JSON.stringify(ret));
      console.log('error:'+JSON.stringify(err));
   }
}

function alert_debug(ret){
   if(debug == 1){
      alert('success:'+JSON.stringify(ret));
   }
}
function create_post_data(arr){
  var version = appversion;
  if(api.systemType == 'android'){
    version == andappversion;
  }
  var data = {"client":api.systemType,"package":apppackage,"version":api.appVersion,"isaes":isaes,"api_key":APP_POST};
  if(arr){
    for(key in arr){
      data[key] = arr[key];
    }
  }

  var clipBoard = api.require('clipBoard');
  clipBoard.set({
      value: JSON.stringify(data)
  }, function(ret, err) {
      api.toast({
          msg: lan['Submission_Prompt'],
          location: 'middle'
      });
  });
  //console_debug(data,data);
  return  JSON.stringify(data).replace(/\s+/g, ' ');
}
function create_submit_data(arr){
  var data = {"client":api.systemType,"lang":lkey,"version":api.appVersion,"EpicorAddress":getapi(),"WMSAddress":wmsserver};
  data.data = arr;

  var clipBoard = api.require('clipBoard');
  clipBoard.set({
    value: JSON.stringify(data)
  }, function(ret, err) {
    api.toast({
      msg:lan['Submission_Prompt'],
      location: 'middle'
  });
});
  console_debug(data,"提交数据");
  return  JSON.stringify(data).replace(/\s+/g, ' ');
}

function get_submit_data(arr){
  var data = {"client":api.systemType,"lang":lkey,"version":api.appVersion,"EpicorAddress":getapi(),"WMSAddress":wmsserver};
  data.data = arr;

  var clipBoard = api.require('clipBoard');
  clipBoard.set({
    value: JSON.stringify(data)
  }, function(ret, err) {
    console.log(JSON.stringify(ret))
});
  console_debug(data,"提交数据");
  return  JSON.stringify(data).replace(/\s+/g, ' ');
}



function output_html(key,data){
  var evalData = doT.template($api.html($api.byId(key+'-template')));
  //console_debug(evalData(data),'');
  //var evalData = doT.template($("#"+key+"-template").html());
  $("#"+key+"-content").html(evalData(data));
}
function append_html(key,data){
  var evalData = doT.template($api.html($api.byId(key+'-template')));
  //console_debug(evalData,'');
  //var evalData = doT.template($("#"+key+"-template").html());
  $("#"+key+"-content").append(evalData(data));
}

function str_today(){
   var myDate = new Date();
   var m = myDate.getMonth()+1;
   if(m<10){
     m = '0' + String(m)
   }
   var d = myDate.getDate();
   if(d<10){
     d = '0' + String(d)
   }
   var today = String(myDate.getFullYear()) + String(m) + String(d);
   return today;
}

function insert_cfc_record(type,process,amount,user_id){
      var db = api.require('db');
      var ret = db.selectSqlSync({name: 'cfc',sql: 'INSERT INTO cfcrecord VALUES ("'+user_id+'","'+process+'", "'+type+'", "'+str_today()+'", "'+amount+'")'});
      return ret.status;
}

function get_cfc_count(type,user_id){
      var db = api.require('db');
      var total = 0;
      var ret = db.selectSqlSync({name: 'cfc',sql: 'SELECT count(*) as total FROM cfcrecord where process = "1" and user_id = "'+user_id+'" and type = "'+type+'" and date ='+str_today()});
      if(ret.status == true){
         total = ret.data[0].total;
      }
      return total;
}


function toActivity(ob){
  var data = {};
  data.bounces = 1;
  data.frame = 'activity_detial';
  data.id = $(ob).attr("data-id");
  data.title = $(ob).attr("data-title");
  data.text = $(ob).attr("data-text");
  data.cacheimg = $(ob).attr("data-cacheimg");
    data.location = $(ob).attr("data-location");
    data.date = $(ob).attr("data-date");
  data.url = $(ob).attr("data-url");
  data.link = $(ob).attr("data-link");
  data.pagetitle = '活动详情';
  //data.is_collection = $(ob).attr("data-collection");
  openWin ('post'+data.id,'./common_header.html',data);
}

function toTags(ob){
  var data = {};
  data.bounces = 1;
  data.frame = 'tag_list';
  data.title = $(ob).attr("data-title");
  data.is_collection = $(ob).attr("data-collection");

  data.pagetitle = $(ob).attr("data-title");
  //data.is_collection = $(ob).attr("data-collection");
  openWin ('post'+data.id,'./common_header.html',data);
}


function toTag(ob){
  var data = {};
  data.bounces = 1;
  data.frame = 'post_list';
  data.title = $(ob).attr("data-title");
  data.name = $(ob).attr("data-title");
  data.is_collection = parseInt($(ob).attr("data-collection"));
  data.pagetitle = $(ob).attr("data-title");
  data.tag_id = $(ob).attr("data-id");
  data.image = $(ob).attr("data-image");
  data.count = $(ob).attr("data-count");
  data.follow = $(ob).attr("data-follow");
  data.bg = $(ob).attr("data-bg");
  //data.is_collection = $(ob).attr("data-collection");
  openWin ('tag'+data.id,'./tag_header.html',data);
}


function toWins(ob){
  var login = parseInt($(ob).attr("data-login"));
  if(login){
      userinfo = get_user_info();
      if(!userinfo.Token){
          toLogin();
      }
  }
  var header = 'common_header';
  if($(ob).attr("data-header")){
    header = $(ob).attr("data-header");
  }
  var title = $(ob).attr("data-title");
  var frame = $(ob).attr("data-frame");
  var bounces = $(ob).attr("data-bounces");
  var Param = {bounces:bounces,frame:frame,title:title};
  var path = api.wgtRootDir+'/html/'+header+'.html';
  openWin (frame,path,Param)

}

function toSearch(ob){
  var type = $(ob).attr("data-type");
  var index = $(ob).attr("data-index");
   openWin ('search',api.wgtRootDir+'/html/common_header_search.html',{index:index,type:type,frame:'search_empty'});
}


function update_search_history(keyword,type){
  var key = 'postsearch';
  if(api.pageParam.type == 'post'){
       key = 'postsearch';
  }
  if(api.pageParam.type == 'wallpaper'){
       key = 'wallpapersearch';
  }
  var historysearch = get_prefs_data(key);
  if(!historysearch){ historysearch = []; }
  if($.inArray(keyword.toString(),historysearch) == -1){
        historysearch.push(keyword);
        api.setPrefs({ key : key,value : historysearch});
        api.sendEvent({name : 'search_update',extra : 'update'});
  }

}
function read_history(id){
  var history = [];
  post_history = get_prefs_data('post_history');
  if(!post_history){
     history.push(id);
     api.setPrefs({  key : 'post_history',value : history});

  }else{
    if($.inArray(id.toString(),post_history) == -1){
         post_history.push(id);
         api.setPrefs({  key : 'post_history',value : post_history});
    }
  }
  console_debug(history,post_history);
}


function get_select_array(data,key,value){
   var param = {};
   var arr = [];
   for(i in data){
      if(data[i][value] == ""){
        data[i][value] = data[i][key];
      }
      param[data[i][key]] = data[i][value]
   }
   for(k in param){
      var row = {};
      row.id = k;
      row.val = param[k];
      arr.push(row);
   }
   return arr;
}

function formatDate(date){
  if(!date){
    return '';
  }
  if(date && date.indexOf("T") == -1 ){
      return date;
  }
  var arr = date.split("T");
  if(arr[0]){
    return arr[0];
  }else{
    return date;
  }
}
function formatDate2(date){
  var arr = date.replace("/","-");
  arr = arr + 'T00:00:00';
  return arr;
}

function formatNumber(num){
  var num1  = parseFloat(num);
  return num1.toFixed(2);
}


function uuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }

function check_empty_row(data){
  console_debug(data, '');
  var error = 0;
  for(i in data){
    for (let k in data[i]) {
       if(k != "Key1" && k != "Key2" && k != "Key3" && k != "Key4" && k != "Key5"){
         if(data[i][k] == ""){
            error = 1;
            break;
         }
       }

    }
    if(error == 1){
      break;
    }
  }
  return error;
}

function _msg(txt){
  api.toast({msg:txt,location: 'middle'});
}



function hasPermission(one_per){
        var perms = new Array();
        perms.push(one_per);
        var rets = api.hasPermission({
            list:perms
        });
        return rets;
}
function confirmPer(perm){
        var has = hasPermission(perm);
        if(!has || !has[0] || !has[0].granted){
          if(perm == 'storage'){
            api.toast({msg:'请开启储存权限',location: 'middle'});
          }
          reqPermission(perm);
          return false;
        }
        return true;
}



function reqPermission(one_per, callback){
        var perms = new Array();
        perms.push(one_per);
          api.requestPermission({
            list: perms,
            code: 100001
          }, function(ret, err){
            if(callback){
              callback(ret);
              return;
            }
            var str = '请求结果：\n';
            str += '请求码: ' + ret.code + '\n';
            str += "是否勾选\"不再询问\"按钮: " + (ret.never ? '是' : '否') + '\n';
            str += '请求结果: \n';
            var list = ret.list;
            for(var i in list){
              str += list[i].name + '=' + list[i].granted + '\n';
            }
            //apialert(str);
            console.log(JSON.stringify(ret));
       });
}


  function timenow(){
      //获取当前时间
      var d = new Date();
      //包装年月日的格式
      var a = d.getFullYear() + "-";
      //月是从零开始的所以得加1，并且判断月份是否大于等于10月，如果大于十月得个前面加零来跟格式匹配
      if (d.getMonth() + 1 >= 10 ){
        var c = (d.getMonth() + 1) + "-";
      }
      else{
        var c = "0" + (d.getMonth() + 1) + '-';
      }
      //不能使用getDay()方法得原因是因为他获取的是今天星期几，只有7天
      if (d.getDate() >= 10 ){
          var n = d.getDate();
      }
      else{
          var n = "0" + d.getDate();
      }
      //给input设置id属性，抓取属性值改变value的值
      return a + c + n;
  }
  function timeTop(data){
    const date = new Date(data);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 注意月份从0开始，需要加1
    const day = String(date.getDate()).padStart(2, '0');
    const formattedDate = `${year}-${month}-${day}`;
    return formattedDate
  }
  //批次属性查询时间截取 2023-06-29T00:00:00 转换 20
  function formatted_time(t){
    const date = new Date(t);
    // 将日期对象格式化为所需的字符串格式
    var time = date.getFullYear() + '-' + (date.getMonth() + 1).toString().padStart(2, '0') + '-' + date.getDate().toString().padStart(2, '0');
    return time
  }

  function create_barcode(t){
    var d = new Date();
    var year = d.getFullYear();
    var month = (d.getMonth() + 1).toString().padStart(2, '0');
    var day = d.getDate().toString().padStart(2, '0');
    var l = t.length;
    
    var s = l - 9;
    
    var str = t.substr(s,9);
    console_debug(t,str);
    if (['CONS', 'KSH', 'KSX', 'KSHBO'].includes(userinfo.Company)) {
      var code = 'PR-' + year + month + day + '-' + str;
    } else {
      var code = 'PR-' + year + '-' + str;
    }
    return code;
  }


  function create_barcode2(t){
    var d = new Date();
    var year = d.getFullYear();
    var month = (d.getMonth() + 1).toString().padStart(2, '0');
    var day = d.getDate().toString().padStart(2, '0');
    var l = t.length;
    
    var s = l - 9;
    
    var str = t.substr(s,9);
    console_debug(t,str);
    if(['CONS',  'KSH', 'KSX', 'KSHBO'].includes(userinfo.Company)){
      var code = 'TR-' + year + month + day+'-'+str;
     }else{
      var code = 'TR-' + year + '-'+str;
     }
    return code;
  }


  function save_label(item){
    api.ajax({
      url: wmsserver + 'packagestatus/',
      method: 'post',
      returnAll: false,
      headers: {
          'token': wmstoken,
          'Content-Type': 'application/json;charset=utf-8'
      },
      data: {
          body: JSON.stringify(item)
      }
      //data: {values: data1}
  }, function (ret, err) {
      ajaxing = 0;
      console_debug(ret, err);
      tagspostcount++;


      if (ret) {
          if (tagspostcount == tags.length) {
              
              api.alert({
                  title: lan['Tips'],
                  msg: lan['Submitted_successfully']
              }, function (ret, err) {
                  
              });
              
              hideProgress();
          }

      } else {
          hideProgress();
          api.toast({
              msg: lan['label_Failed'],
              location: 'middle'
          });
      }

  });
  }


  function update_label(item){
    api.ajax({
      url: wmsserver + 'packagestatus/',
      method: 'put',
      returnAll: false,
      headers: {
          'token': wmstoken,
          'Content-Type': 'application/json;charset=utf-8'
      },
      data: {
          body: JSON.stringify(item)
      }
      //data: {values: data1}
  }, function (ret, err) {
      ajaxing = 0;
      if (ret) {
        hideProgress();
      } else {
          hideProgress();
          api.toast({
              msg: lan['label_Failed'],
              location: 'middle'
          });
      }

  });
  }


  function Upper_arr(arr){
     var arr1 = [];
     for(i in arr){
       var row = arr[i];
       var item = {};
       for(key in row){
           var k = key.slice(0,1).toUpperCase() + key.slice(1);
           item[k] = row[key];
       }
       arr1.push(item);
     }
     return arr1;
  }

  function post_Tags_obj(item) {
    let object = {
        "LotNum": item.LotNum || "",
        "NonConfID": item.NonConfID || 0,
        "TranDate": item.TranDate || timenow(),
        "OrderRelNum": item.OrderRelNum || 0,
        "ShelfNum": item.ShelfNum || "",
        "POLine": item.POLine || 0,
        "DMRNum": item.DMRNum || 0,
        "OrderLine": item.OrderLine || 0,
        "PackageID": item.PackageID || "",
        "JobSeq": item.JobSeq || 0,
        "PartNum": item.PartNum || "",
        "ToWarehouseCode": item.ToWarehouseCode || "",
        "TranTime": item.TranTime || 0,
        "ActionNum": item.ActionNum || 0,
        "ToBinNum": item.ToBinNum || "",
        "PackNum": item.PackNum || 0,
        "PORelNum": item.PORelNum || 0,
        "FromWarehouseCode": item.FromWarehouseCode || "",
        "OrderNum": item.OrderNum || 0,
        "PackLine": item.PackLine || 0,
        "TranType": item.TranType || "",
        "PONum": item.PONum || 0,
        "FromBinNum": item.FromBinNum || "",
        "PartDescription": item.PartDescription || "",
        "LabelNum": item.LabelNum || "",
        "Company": item.Company || "",
        "AssemblySeq": item.AssemblySeq || 0,
        "TranQty": item.TranQty || 0,
        "IUM": item.IUM || "",
        "PackSlip": item.PackSlip || "",
        "RMANum": item.RMANum || 0,
        "JobNum": item.JobNum || ""
    };

     // 将缺失的字段填充到原对象中
     for (let key in object) {
          if (!(key in item)) {
              item[key] = object[key];
          }
      }

      return item;
}


  function get_new_arr(arr){
    var ar = {};
    for(key in arr){
      ar[key] = arr[key];
    }
    return ar;
  }
  


  Date.prototype.Format = function (fmt) { // author: meizz
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
}


function open_printpage(print_tags,print_num,print_type){
  var data = {};
  data.tags = print_tags;
  data.type = print_type;
  data.print_num = print_num;
  data.title = print_type == 3 ? lan['Print_SN_Label']:lan['Print_Label'];
  data.frame = "printpage";
  data.right = [{
          text: lan['Reset'],
          color: '#fff',
  }];
  openNavWin2(data.frame, data);
}

function open_printpage4(print_tags,print_num,print_type,print_codes){
  var data = {};
  data.tags = print_tags;
  data.codes = print_codes
  data.type = print_type;
  data.print_num = print_num;
  data.title = print_type == 3 ? lan['Print_NO_SN_Label']:lan['Print_Label'];
  data.frame = "printpage";
  data.right = [{
          text: lan['Reset'],
          color: '#fff',
  }];
  openNavWin2(data.frame, data);
  
}

function open_printpage2(print_tags,print_num,print_type,carton_type,mode_type){
  var data = {};
  data.tags = print_tags;
  data.type = print_type;
  data.carton_type = carton_type;
  data.mode_type = mode_type;
  data.print_num = print_num;
  data.title = print_type == 3 ? lan['Print_SN_Label']:lan['Print_Label'];
  data.frame = "printpage";
  data.right = [{
          text: lan['Reset'],
          color: '#fff',
  }];
  openNavWin2(data.frame, data);
  
}

function open_printpage3(print_tags,print_num,print_type){
  var data = {};
  data.tags = print_tags;
  data.type = print_type;
  data.print_num = print_num;
  data.title = print_type == 3 ? lan['Print_SN_Label']:lan['Print_Label'];
  data.frame = "printpagechg";
  data.right = [{
          text: lan['Reset'],
          color: '#fff',
  }];
  openNavWin2(data.frame, data);
}

function get_ProdCode(item) {

  return new Promise((resolve) => {

      api.ajax({
          url: server + 'Erp.BO.PartSvc/Parts(' + userinfo.Company + ',' + item.PartNum + ')',
          method: 'get',
          returnAll: false,
          headers: {
              'Authorization': userinfo.Token,
              'Content-Type': 'application/json;charset=utf-8'
          },
          data: {}
      }, function (ret, err) {
          ajaxing = 0;
          console_debug(ret, "Erp.BO.PartSvc/Parts");
          var ProdCode = "";
          if (ret) {
              ProdCode = ret.ProdCode;
          }
          resolve(ProdCode);

      });



  })

}

function processNumber(input, value) {
  // 如果输入为空或不是数字类型，返回 0
  if (!input && input !== 0) {
    return 0;
  }

  // 如果输入是字符串，尝试将其转换为数字类型
  if (typeof input === 'string') {
    input = parseFloat(input);
  }

  // 如果输入是数字，并且有小数点，而且小数位数超过 value，则保留小数位数到 value 并四舍五入
  if (typeof input === 'number' && input % 1 !== 0) {
    const decimalCount = (input.toString().split('.')[1] || '').length || 0;
    if (decimalCount > value) {
      const roundedValue = input.toFixed(value);
      return parseFloat(roundedValue);
    }
  }

  return input; // 默认情况，返回输入值
}




//检验逻辑处理

function InspectBlocking(ret) {
  if (ret[0].Trantype !== "PUR-INS" && ret[0].Trantype !== "STK-INS") {
    if (ret[0].onhandQty == 0 || ret[0].Trantype == "DMR-REJ") {
      api.toast({
        msg: lan['Invalid_placeholder'],
        location: 'middle'
      });
      return false; // 阻断了操作，返回false
    }
    if (ret[0].Trantype === "INS-DMR") {
      api.toast({
        msg: lan['DMR_placeholder'],
        location: 'middle'
      });
      return false; // 阻断了操作，返回false
    }
    if (ret[0].Trantype == "STK-PLT") {
      api.toast({
        msg: lan['In_Transit_placeholder'],
        location: 'middle'
      });
      return false; // 阻断了操作，返回false
    }
  } else {
    api.toast({
      msg: lan['Pending_Inspection_placeholder'],
      location: 'middle'
    });
    return false; // 阻断了操作，返回false
  }
  
  return true; // 执行到这里表示没有阻断操作，返回true
}
//箱/托/物料条码查询 状态映射
const statusMap = {
  'PUR-INS': { text: 'Inspection', class: 'btn-danger' },
  'STK-INS': { text: 'Inspection', class: 'btn-danger' },
  'STK-PLT': { text: 'In_Transit', class: 'btn-success' },
  'INS-DMR': { text: 'DMR', class: 'btn-warning', color: '#fff' },
  'DMR-STK': { text: 'Valid', class: 'btn-primary', color: '#fff' },
  'DMR-REJ': { text: 'Invalid', class: 'btn-secondary' }
};

function errMassage(msg) {
  let chineseReg = /[\u4e00-\u9fa5]/; // 包含中文的正则表达式
  if (chineseReg.test(msg)) { // 如果msg中包含中文
    console.log(msg);
    api.confirm({
      title: lan["Tips"],
      msg: msg,
      buttons: ["", lan["YES"]],
    },function (ret, err) {
        // 用户点击了 "YES"，继续提交数据或执行相应的操作
        // 在这里编写用户点击 "YES" 后的处理逻辑
    });
    return
  } else {
    let chineseErrorMessage = msg.match(/[\u4e00-\u9fa5]+/); // 提取中文错误信息

    if (chineseErrorMessage !== null) {
      console.log(chineseErrorMessage[0]);
      api.confirm({
        title: lan["Tips"],
        msg: chineseErrorMessage[0],
        buttons: ["", lan["YES"]],
      },function (ret, err) {
          // 用户点击了 "YES"，继续提交数据或执行相应的操作
          // 在这里编写用户点击 "YES" 后的处理逻辑
      });
      return
    } else {
      const remainingChars = msg.substr(0,300);
      api.confirm({
        title: lan["Tips"],
        msg: remainingChars,
        buttons: ["", lan["YES"]],
      },function (ret, err) {
          // 用户点击了 "YES"，继续提交数据或执行相应的操作
          // 在这里编写用户点击 "YES" 后的处理逻辑
      });
      return
    }
  }
}


function user_Permissions(permissionData) {
  return new Promise(function(resolve, reject) {
    var data1 = {
      "CompanyID": userinfo.Company,
      "PlantID": userinfo.Site,
      "UserName": userinfo.Name,
      "Password": userinfo.password,
      "Data":"",
    };
    api.ajax({
      url: wmsserver + 'getlicenceinfo/',
      method: 'post',
      returnAll: false,
      headers: {
        'token': wmstoken,
        'Content-Type': 'application/json;charset=utf-8'
      },
      data: {
        body: get_submit_data(data1)
      }
    }, function (ret, err) {
      console.log(JSON.stringify(ret),11111)
      if (ret) {
        // 判断是否在报警时间范围内
        if (new Date(ret.data.CurrentDate) >= new Date(ret.data.AlertDate) && new Date(ret.data.CurrentDate) < new Date(ret.data.StopDate)) {
          let timeDiff = Math.ceil((new Date(ret.data.StopDate) -new Date(ret.data.CurrentDate)) / (1000 * 60 * 60 * 24));
          let msg = lan['Warning_prompt_front'] + timeDiff + lan['Warning_prompt_after'] + '\n\n' + lan['Please_license_keyrenewal']  ;
          api.confirm({
            title: lan['Temporary_License_Expiry'],
            msg: msg,
            buttons: [lan['Cancel'],lan['Comfirm']]
          }, function (ret, err) {
            var index = ret.buttonIndex;
            if (index === 2) {
              reject(lan['Warning_prompt_front'] + timeDiff + lan['Warning_prompt_after']);
              openNavWin2(permissionData.frame,permissionData)
            }
          });
        } else if (new Date(ret.data.CurrentDate) >= new Date(ret.data.StopDate)) {
          let msg = lan['Blocking_prompt_placeholder'];
          api.confirm({
            title: lan['Temporary_License_Expiry'] + '\n\n' + lan['Please_license_keyrenewal'],
            msg: msg,
            buttons: [lan['Cancel'],lan['Comfirm']]
          }, function (ret, err) {
            var index = ret.buttonIndex;
            if (index === 2 || index === 1) {
              reject(lan['Blocking_prompt_placeholder']);
            }
          });
        } else {
          resolve("权限判断通过");
        }
      }
    });
  });
}

function LoginIn_Usergetlic(data, callback) {
  let data1 = {
      DeviceID: data.DeviceID,
      AppType: "WMS",
      LicQty:data.LicQty || localStorage.getItem('LicQty')
  }

  api.ajax({
      url: wmsserver + 'usergetlic/',
      method: 'post',
      returnAll: false,
      dataType: 'text',
      headers: {
          'token': wmstoken,
          'Content-Type': 'application/json;charset=utf-8'
      },
      data: {
          body: JSON.stringify(data1)
      }
  }, function(ret, err) {
      console.log(JSON.stringify(data1),33333)
      console.log(JSON.stringify(ret),222222)
      if (ret) { // 判断ret是否为空
        callback(ret);
      } else {
          // 执行错误处理，并返回提示信息
          callback(null); // 或者可以使用 callback("") 作为错误标识
      }
  });
}

function Loginout_Userdellic(data){
  let data1={
    DeviceID:data.DeviceID,
    AppType:"WMS",
    LicQty:localStorage.getItem('LicQty')	 || 0
  }

  api.ajax({
    url: wmsserver + 'userdellic/',
    method: 'post',
    returnAll: false,
    dataType: 'text',
    headers: {
        'token': wmstoken,
        'Content-Type': 'application/json;charset=utf-8'
    },
    data: {
        body: JSON.stringify(data1)
    }
  }, function (ret, err) {
    console.log(JSON.stringify(data1),33333)
    console.log(JSON.stringify(ret),4444444)
    if (ret) {
    }
  });

}


function Loginout_Userchklic(data,callback){
  let data1={
    DeviceID:data.DeviceID,
    AppType:"WMS",
    LicQty:localStorage.getItem('LicQty')	 || 0
  }

  api.ajax({
    url: wmsserver + 'userchklic/',
    method: 'post',
    returnAll: false,
    dataType: 'text',
    headers: {
        'token': wmstoken,
        'Content-Type': 'application/json;charset=utf-8'
    },
    data: {
        body: JSON.stringify(data1)
    }
  }, function (ret, err) {
    console.log(JSON.stringify(data1),33333)
    console.log(JSON.stringify(ret),33333)
    if (ret) { // 判断ret是否为空
      callback(ret);
    } else {
        // 执行错误处理，并返回提示信息
        callback(null); // 或者可以使用 callback("") 作为错误标识
    }
  });

}